package com.module.base.base.loadsir;

import android.view.View;

import com.module.base.network.ERROR;
import com.module.base.network.exception.ServerException;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.callback.SuccessCallback;
import com.kingja.loadsir.core.Convertor;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;

/**
 * @author bsnl_yanxuwen
 * @date 2021/3/19 16:51
 * Description :
 * 缺省图统一创建方法
 */
public class LoadSirRegister {
    public static LoadService register(LoadSirReloadListener listener, Object target) {
        final boolean[] isErrorView = {false};
        LoadService loadService = LoadSir.getDefault().register(target, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                // 重新加载逻辑，空视图不做加载
                if (listener != null && isErrorView[0]) {
                    listener.reload();
                }
            }
        }, new Convertor<ServerException>() {
            @Override
            public Class<? extends Callback> map(ServerException exception) {
                Class<? extends Callback> resultCode = SuccessCallback.class;
                if (exception != null) {
                    int emptyCode = ERROR.INSTANCE.getEMPTY();
                    if (exception.getCode() == emptyCode) {
                        isErrorView[0] = false;
                        resultCode = listener.getEmptyCallback();
                    } else {
                        isErrorView[0] = true;
                        ErrorViewUtils.putError(exception);//设置缺省图错误信息
                        resultCode = listener.getErrorCallback();
                    }
                } else {
                    isErrorView[0] = true;
                    resultCode = listener.getErrorCallback();
                }
                return resultCode;
            }
        });
        return loadService;
    }

}
